
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import be.InsertList;
import be.Table;
import be.db_backend;


/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public TestServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		db_backend db = new db_backend();
		
		if(request.getParameter("CreatetableName") != null){
			String tableName = request.getParameter("CreatetableName");
			Table tab = new Table();
			
			if(request.getParameter("var1name") != null && request.getParameter("var1name") != "")
				tab.addVariable(request.getParameter("var1name"), request.getParameter("var1type"));
			if(request.getParameter("var2name") != null && request.getParameter("var2name") != "")
				tab.addVariable(request.getParameter("var2name"), request.getParameter("var2type"));
			if(request.getParameter("var3name") != null && request.getParameter("var3name") != "")
				tab.addVariable(request.getParameter("var3name"), request.getParameter("var3type"));
			if(request.getParameter("var4name") != null && request.getParameter("var4name") != "")
				tab.addVariable(request.getParameter("var4name"), request.getParameter("var4type"));
			
			db.CreateTable(tableName, tab);
		}
		
		if(request.getParameter("blobfile") != null){
			
			
			String test = "C:\\Users\\LURKEN\\Desktop\\Spel\\stuff\\";
			String filePath = test + request.getParameter("blobfile");
						
			System.out.println(filePath);
			
			File a = new File(filePath);
			
			FileInputStream stream = new FileInputStream(a);
			
			db.storeBLOB("blob", stream);
			
			
		}
		
		if(request.getParameter("getDataTableName") != null){
			
			String tableName = request.getParameter("getDataTableName");
			String data = request.getParameter("data"); 
			
			ResultSet ret = db.getData(tableName, "*", data);
			out.print("<p>Result from table: " + tableName + ", with data: " + data+":</p>");
			printTableFromGetData(ret, out);
			
		}
		
		if(request.getParameter("InsertTableName") != null){
			String tableName = request.getParameter("InsertTableName");
			
			InsertList insert = new InsertList();
			
			if(request.getParameter("var1name") != null && !request.getParameter("var1name").equals(""))
				insert.addVariable(request.getParameter("var1name"), request.getParameter("var1type"),request.getParameter("var1value"));
			if(request.getParameter("var2name") != null && !request.getParameter("var2name").equals(""))
				insert.addVariable(request.getParameter("var2name"), request.getParameter("var2type"),request.getParameter("var2value"));
			if(request.getParameter("var3name") != null && !request.getParameter("var3name").equals(""))
				insert.addVariable(request.getParameter("var3name"), request.getParameter("var3type"),request.getParameter("var3value"));
			if(request.getParameter("var4name") != null && !request.getParameter("var4name").equals(""))
				insert.addVariable(request.getParameter("var4name"), request.getParameter("var4type"),request.getParameter("var4value"));
			
			
			db.Insert(tableName, insert);
			
			ResultSet ret = db.getData(tableName, "*","");
			out.print("<p>Result from table: " + tableName + ":</p>");
			printTableFromGetData(ret, out);
			
		}
		
		if(request.getParameter("deleteDataTableName") != null){
			String tableName = request.getParameter("deleteDataTableName");
			String data = request.getParameter("data"); 
			
			db.deleteData(tableName, data);
						
			ResultSet ret = db.getData(tableName, "*","");
			out.print("<p>Result from table: " + tableName + ", after deletion:</p>");
			printTableFromGetData(ret, out);
			
			
		}
		
		
		out.println("<a href='/db_labb1/index.jsp'> Back to index!</a>");

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		db_backend db = new db_backend();
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();

                        String root = getServletContext().getRealPath("/");
                        root = "";
                        File path = new File(root + "/uploads");
                        
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        
                        item.write(uploadedFile);
                        
                        FileInputStream stream = new FileInputStream(uploadedFile);
                        db.storeBLOB("blob", stream);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
	}
	
	public void printTableFromGetData(ResultSet input, PrintWriter out){
		try {
			if (input != null) {
				out.println("<table>");
				
				ArrayList<String> result = new ArrayList<String>();
				ResultSetMetaData meta = input.getMetaData();
				
				int numColumns = meta.getColumnCount();

				String columns = "";
				for (int i = 1; i < numColumns + 1; i++) {
					columns += meta.getColumnName(i) + " ";
				}
				result.add(columns);

				String row;
				while (input.next()) {
					row = "";
					for (int i = 1; i < numColumns + 1; i++)
						row += input.getObject(meta.getColumnName(i)) + " ";
					result.add(row);
				}
				out.println(result);
				out.println("</table>");
			} else {
				out.println("Empty result from database!");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
